package com.semp.jadoma.admin.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;

import com.semp.jadoma.admin.bean.AdminBean;
import com.semp.jadoma.admin.bm.model.Admin;
import com.semp.jadoma.admin.bm.service.AdminService;
import com.semp.jadoma.admin.form.LoginForm;
import com.semp.jadoma.admin.utils.webapp.Forward;
import com.semp.jadoma.admin.utils.webapp.Keys;
import com.semp.jadoma.admin.utils.webapp.Session;

public class LoginAction extends RootAction implements UnexpireInterface {

	private final static Logger logger = Logger.getLogger(LoginAction.class);
	
	@Override
	public String executeChild(ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		LoginForm loginForm = (LoginForm) form;
		
		Admin admin = AdminService.findByLogin(loginForm.getLogin());
		if (admin == null) {
			logger.info("User " + loginForm.getLogin() + " not found");
			return forwardError(request, Keys.ERROR_LOGIN);
		} else if (!admin.getPassword().equals(loginForm.getPassword())) {
			logger.info("User " + loginForm.getLogin() + ", wrong password");
			return forwardError(request, Keys.ERROR_LOGIN);
		} else {
			request.getSession().setAttribute(Session.BEAN_ADMIN, new AdminBean(admin));
			logger.info("Authentication success for user " + admin.getLogin());
			return Forward.SUCCESS;
		}
		
	}

}
